package com.lagou.springboot_homework.application;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.startup.Tomcat;

import java.io.File;

/**
 * @ClassName: SpringApplication
 * @Description: TODO
 * @Date: 2021/3/22 22:06
 * @Create by: shuiren
 */
public class SpringApplication {

    public static void run(Class<?> primarySource, String... args) {
        new SpringApplication().run(args);
    }

    private void run(String[] args) {
        try {
            Tomcat tomcat = new Tomcat();
            tomcat.setPort(8082);
            File baseDir =  createTempDir("tomcat");
            Context context = tomcat.addContext("/", baseDir.getAbsolutePath());
            context.addLifecycleListener((LifecycleListener) Class.forName(tomcat.getHost().getConfigClass())
                    .getConstructor().newInstance());
            tomcat.start();
            tomcat.getServer().await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private  File createTempDir(String prefix) {
        try {
            File tempDir = File.createTempFile(prefix + ".", ".80");
            tempDir.delete();
            tempDir.mkdir();
            tempDir.deleteOnExit();
            return tempDir;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
